package com.grapes.view;

import java.util.LinkedList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.grapes.R;
import com.grapes.business.CompanyRelativeBusiness;
import com.grapes.model.Comment;
import com.grapes.model.NetApplication;
import com.grapes.model.Student;
import com.grapes.widget.GrapesHeadIconImgView;

public class RecruiteInfoDetailActivity extends GrapesActivity {

	private String companyId;
	private String companyName;
	private List<Comment> comments;
	private List<Student> favoritors;
	private NetApplication netApplication = null;
	public static final String INTENT_PARAM_COMPANY_ID = "CompanyId";
	public static final String INTENT_PARAM_COMPANY_NAME = "CompanyName";
	public static final int MSG_LOAD_COMMENTOR_OK = 1;
	public static final int MSG_LOAD_FAVORITOR_OK = 2;
	public static final int MSG_LOAD_NET_APPLICATION_OK = 3;
	public static final int MSG_LOAD_COMMENTOR_FAIL = 4;
	public static final int MSG_LOAD_FAVORITOR_FAIL = 5;
	public static final int MSG_LOAD_NET_APPLICATION_FAIL = 6;

	public Handler hander = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			switch (msg.what) {
			case MSG_LOAD_COMMENTOR_OK:
			case MSG_LOAD_COMMENTOR_FAIL:
				loadCompanyFavoritors();
				break;
			case MSG_LOAD_FAVORITOR_OK:
			case MSG_LOAD_FAVORITOR_FAIL:
				loadCompanyNetApplication();
				break;
			case MSG_LOAD_NET_APPLICATION_OK:
			case MSG_LOAD_NET_APPLICATION_FAIL:
				dismissPorgressDialog();
				fillUpComponentInfo();
				addFavoritorPhotos();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recruite_info_detail);
		adjustComponentSize();
		companyId = getIntent().getStringExtra(INTENT_PARAM_COMPANY_ID);
		companyName = getIntent().getStringExtra(INTENT_PARAM_COMPANY_NAME);
		comments = new LinkedList<Comment>();
		favoritors = new LinkedList<Student>();
		showProgressDialog();

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					comments = CompanyRelativeBusiness.getInstance()
							.getFakedCompanyRelativeComments(companyId);
					Message msg = new Message();
					msg.what = MSG_LOAD_COMMENTOR_OK;
					hander.sendMessage(msg);
				} catch (Exception e) {
					Message msg = new Message();
					msg.what = MSG_LOAD_COMMENTOR_FAIL;
					hander.sendMessage(msg);
				}
			}
		}).start();

	}

	private void adjustComponentSize() {
		int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
		int horizontalMargin = 15;
		RelativeLayout leftGroup = (RelativeLayout) findViewById(R.id.recruite_miscellaneous_info_left_group);
		RelativeLayout rightGroup = (RelativeLayout) findViewById(R.id.recruite_miscellaneous_info_right_group);
		leftGroup.getLayoutParams().width = (screenWidth - horizontalMargin * 3) / 2;
		((RelativeLayout.LayoutParams) leftGroup.getLayoutParams()).leftMargin = horizontalMargin;
		((RelativeLayout.LayoutParams) leftGroup.getLayoutParams()).rightMargin = horizontalMargin;
		rightGroup.getLayoutParams().width = leftGroup.getLayoutParams().width;
		rightGroup.getLayoutParams().height = leftGroup.getLayoutParams().height;
		((RelativeLayout.LayoutParams) rightGroup.getLayoutParams()).rightMargin = horizontalMargin;
	}

	private void loadCompanyFavoritors() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					favoritors = CompanyRelativeBusiness.getInstance()
							.getFakedCompanyFavoritors(companyId);
					Message msg = new Message();
					msg.what = MSG_LOAD_FAVORITOR_OK;
					hander.sendMessage(msg);
				} catch (Exception e) {
					Message msg = new Message();
					msg.what = MSG_LOAD_FAVORITOR_FAIL;
					hander.sendMessage(msg);
				}
			}
		}).start();
	}

	private void loadCompanyNetApplication() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					netApplication = CompanyRelativeBusiness.getInstance()
							.getFakedCompanyNetApplication(companyId);
					Message msg = new Message();
					msg.what = MSG_LOAD_NET_APPLICATION_OK;
					hander.sendMessage(msg);
				} catch (Exception e) {
					Message msg = new Message();
					msg.what = MSG_LOAD_NET_APPLICATION_FAIL;
					hander.sendMessage(msg);
				}
			}
		}).start();
	}

	private void fillUpComponentInfo() {
		TextView title = (TextView) findViewById(R.id.recuite_info_detail_title_txt);
		title.setText(companyName);
		TextView deadline = (TextView) findViewById(R.id.net_application_deadline_content);
		if (netApplication == null) {
			deadline.setText("δ֪");
		} else
			deadline.setText(netApplication.getEndDate() + " "
					+ netApplication.getEndTime());
		ListView listView = (ListView) findViewById(R.id.detail_company_comment_list);
		CommentAdaper adapter = new CommentAdaper();
		listView.setAdapter(adapter);
	}

	private void addFavoritorPhotos() {
		RelativeLayout rightGroup = (RelativeLayout) findViewById(R.id.recruite_miscellaneous_info_right_group);
		if (favoritors.size() == 0) {
			TextView noFavoritorTxt = new TextView(
					RecruiteInfoDetailActivity.this);
			noFavoritorTxt.setText(R.string.no_favorite_alert);
			RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			param.addRule(RelativeLayout.CENTER_IN_PARENT);
			rightGroup.addView(noFavoritorTxt, param);
			return;
		}
		int MAX_LINE_NUMBER = 3;
		int MAX_COLUMN_NUMBER = 3;
		int cellWidth = rightGroup.getWidth() / MAX_COLUMN_NUMBER;
		for (int index = 0; index < favoritors.size(); index++) {
			if (index >= MAX_LINE_NUMBER * MAX_COLUMN_NUMBER) {
				// A number indicator in the center of the RelativeLayout if
				// favoritors exceeds 9 people
				TextView favoritorCountTxt = new TextView(
						RecruiteInfoDetailActivity.this);
				favoritorCountTxt.setText(R.string.no_favorite_alert);
				favoritorCountTxt.setTextColor(R.color.red);
				favoritorCountTxt.setBackgroundColor(R.color.transparent);
				RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				param.addRule(RelativeLayout.CENTER_IN_PARENT);
				rightGroup.addView(favoritorCountTxt, param);
				break;
			}
			final Student student = favoritors.get(index);
			GrapesHeadIconImgView headIcon = new GrapesHeadIconImgView(
					RecruiteInfoDetailActivity.this);
			headIcon.setResourceUrl(student.getIconUrl());
			if (rightGroup.getChildCount() > 0) {
				LinearLayout lastRow = (LinearLayout) rightGroup
						.getChildAt(rightGroup.getChildCount() - 1);
				if (lastRow.getChildCount() > MAX_COLUMN_NUMBER - 1)// each row
																	// can
																	// contain 3
				// buttons at most
				{
					// create a new row
					LinearLayout newRow = new LinearLayout(
							RecruiteInfoDetailActivity.this);
					newRow.setOrientation(LinearLayout.HORIZONTAL);
					LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
							cellWidth, (int) cellWidth / 2);
					newRow.addView(headIcon, param);

					newRow.setId(index);
					RelativeLayout.LayoutParams lineParam = new RelativeLayout.LayoutParams(
							LayoutParams.MATCH_PARENT,
							LayoutParams.WRAP_CONTENT);
					lineParam.addRule(RelativeLayout.BELOW, index - 1);
					rightGroup.addView(newRow, lineParam);
				} else {
					LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
							cellWidth, (int) cellWidth / 2);
					lastRow.addView(headIcon, param);
				}
			} else {
				// create a new row
				LinearLayout newRow = new LinearLayout(
						RecruiteInfoDetailActivity.this);
				newRow.setOrientation(LinearLayout.HORIZONTAL);
				LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
						cellWidth, (int) cellWidth / 2);
				newRow.addView(headIcon, param);

				newRow.setId(index);
				RelativeLayout.LayoutParams lineParam = new RelativeLayout.LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
				lineParam.addRule(RelativeLayout.ALIGN_PARENT_TOP,
						RelativeLayout.TRUE);
				rightGroup.addView(newRow, lineParam);
			}
		}
	}

	private class CellViewHolder {
		GrapesHeadIconImgView headIcon;
		TextView timestampTxt;
		TextView contentTxt;
		TextView replyCountTxt;
		TextView commentNameTxt;
		Button publishCommentBtn;
	}

	class CommentAdaper extends BaseAdapter {
		@Override
		public int getCount() {
			return comments.size();
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			CellViewHolder viewHolder;
			GrapesHeadIconImgView headIcon;
			TextView timestampTxt;
			TextView contentTxt;
			TextView replyCountTxt;
			TextView commentNameTxt;
			Button publishCommentBtn;

			if (convertView == null) {
				convertView = getLayoutInflater().inflate(
						R.layout.comment_item, null);
				viewHolder = new CellViewHolder();
				// TextView
				viewHolder.headIcon = (GrapesHeadIconImgView) convertView
						.findViewById(R.id.company_commentor_icon);
				viewHolder.timestampTxt = (TextView) convertView
						.findViewById(R.id.company_commentor_publish_timestamp);
				viewHolder.contentTxt = (TextView) convertView
						.findViewById(R.id.company_comment_content);
				viewHolder.replyCountTxt = (TextView) convertView
						.findViewById(R.id.company_comment_reply_count);
				viewHolder.commentNameTxt = (TextView) convertView
						.findViewById(R.id.company_commentor_name);
				// Button
				viewHolder.publishCommentBtn = (Button) convertView
						.findViewById(R.id.create_reply_btn);
				convertView.setTag(viewHolder);
			} else
				viewHolder = (CellViewHolder) convertView.getTag();

			headIcon = viewHolder.headIcon;
			timestampTxt = viewHolder.timestampTxt;
			contentTxt = viewHolder.contentTxt;
			replyCountTxt = viewHolder.replyCountTxt;
			commentNameTxt = viewHolder.commentNameTxt;
			publishCommentBtn = viewHolder.publishCommentBtn;

			Comment comment = comments.get(position);
			headIcon.setResourceUrl(comment.getPublisher().getIconUrl());
			timestampTxt.setText(comment.getPublishTimeStamp());
			contentTxt.setText(comment.getContent());
			replyCountTxt.setText(String.valueOf(comment.getAttchedReplies()
					.size()));
			commentNameTxt.setText(comment.getPublisher().getStudentName()
					+ " " + comment.getPublisher().getSchoolName());
			return convertView;
		}
	}
}
